using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using PowerManage.API.Auth;
using PowerManage.API.Exception;
using PowerManage.API.UOW;
using PowerManage.Entity;
using PowerManage.Entity.Dtos.Users;
using PowerManage.Service;
using PowerManage.Service.UOW;

namespace PowerManage.API.Controllers;

/// <summary>
/// 用户
/// </summary>
[Route("api/[controller]")] //用户指定路由前缀 api/user
[PermissionAuthorize]
public class UserController : BaseController
{
    private readonly IUserService _userService;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserManager<EleUser> _userManager;
    private readonly IMapper _mapper;
    private readonly IUnitOfWork _unitOfWork;
    private readonly ILogger _logger;

    public UserController(IUserService userService, IHttpContextAccessor httpContextAccessor,
        UserManager<EleUser> userManager, IMapper mapper, IUnitOfWork unitOfWork, ILoggerFactory loggerFactory)
    {
        _userService = userService;
        _httpContextAccessor = httpContextAccessor;
        _userManager = userManager;
        _mapper = mapper;
        _unitOfWork = unitOfWork;
        _logger = loggerFactory.CreateLogger("MyLogLevel");
        _logger.LogInformation("LogInformation 日志记录");
        _logger.LogWarning("LogWarning 日志记录");
        _logger.LogError("LogError 日志记录");
    }

    /// <summary>
    /// 根据用户名搜索，分页返回用户列表
    /// </summary>
    /// <param name="userPageReqDto"></param>
    /// <returns></returns>
    [HttpGet]
    [UnitOfWork(IsTransactional = false)]
    public async Task<IActionResult> Get([FromQuery] UserPageReqDto userPageReqDto)
    {
        // 根据用户名搜索，分页返回用户列表
        var userPageRspDto = await _userService.GetUserPageAsync(userPageReqDto);
        return Ok(userPageRspDto);
    }

    /// <summary>
    /// 新增用户
    /// </summary>
    /// <param name="userCreateDto"></param>
    /// <returns></returns>
    /// 添加成功：返回201，使用Created方法响应结果，其中Created第一个参数为Url，我们这边默认为空。
    /// 添加失败：返回400，使用BadRequest方法响应结果。
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] UserCreateDto userCreateDto)
    {
        // 新增用户
        var user = _mapper.Map<EleUser>(userCreateDto);

        //获取登录的用户
        var userName = _httpContextAccessor.HttpContext.User.Identity.Name;
        var creatorUser = await _userManager.FindByNameAsync(userName);

        //更新字段
        user.CreatorId = creatorUser.Id;
        user.EmailConfirmed = true; //邮件确认，设置为true，否则无法登录
        user.NormalizedUserName = user.UserName; //用于存储经过规范化处理后的用户名
        user.LockoutEnabled = false; //防止账户被锁定
        user.SecurityStamp = DateTime.Now.Ticks.ToString(); //用于存储与用户相关的安全信息。它通常用于跟踪用户的认证状态和安全相关信息，例如密码哈希、登录尝试次数等
        //使用 passwordHasher 对象的 HashPassword 方法对用户密码进行哈希处理
        var passwordHasher = new PasswordHasher<EleUser>();
        user.PasswordHash = passwordHasher.HashPassword(user, userCreateDto.Password);
        //保存用户 这个方法中的用户名只能是数字和字母
        var result = await _userManager.CreateAsync(user);
        if (result.Succeeded)
        {
            return Created(string.Empty, user);
        }
        else
        {
            var responseResult = new ResponseResultDto().SetError("添加用户失败！");
            return BadRequest(responseResult);
        }
    }

    /// <summary>
    /// 更新用户
    /// </summary>
    /// <param name="id"></param>
    /// <param name="userUpdateDto"></param>
    /// <returns></returns>
    [HttpPut("{id}")]
    // [UnitOfWorkFilter] //配了全局 这个就不需要加了
    // [PowerManageExceptionFilter] 配了全局 这个就不需要加了
    public async Task<IActionResult> Put(long id, [FromBody] UserUpdateDto userUpdateDto)
    {
        //获取用户
        var user = await _userManager.FindByIdAsync(id.ToString());
        if (user == null)
        {
            return BadRequest(new ResponseResultDto().SetError("用户不存在"));
        }

        //更新用户
        if (userUpdateDto.Password == null)
        {
            userUpdateDto.Password = user.PasswordHash;
        }
        else
        {
            user.PasswordHash = new PasswordHasher<EleUser>().HashPassword(user, userUpdateDto.Password);
        }

        _mapper.Map(userUpdateDto, user);
        user.LastModificationTime = DateTime.Now;
        var result = await _userManager.UpdateAsync(user);
        if (!result.Succeeded)
        {
            return BadRequest(new ResponseResultDto().SetError("更新用户失败！"));
        }

        // //模拟异常
        // if (userUpdateDto.UserName == "ceshi")
        // {
        //     throw new System.Exception("模拟异常");
        // }
        //删除原来的角色
        var oldRoles = await _userManager.GetRolesAsync(user);
        if (oldRoles != null && oldRoles.Count > 0)
        {
            await _userManager.RemoveFromRolesAsync(user, oldRoles);
        }

        //设置新的角色列表
        result = await _userManager.AddToRolesAsync(user, userUpdateDto.RoleNames);

        if (result.Succeeded)
        {
            return NoContent();
        }
        else
        {
            return BadRequest(new ResponseResultDto().SetError("更新用户失败！"));
        }
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    /// {id} 是一个路径参数，表示 URL 中的一部分。
    /// 当客户端发送一个 DELETE 请求到 /api/users/{id} 时，这个方法会被调用
    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(long id)
    {
        var user = await _userManager.FindByIdAsync(id.ToString());
        if (id == 1)
        {
            return BadRequest(new ResponseResultDto().SetError("超级管理员不允许删除！"));
        }
        else if (user == null)
        {
            return BadRequest(new ResponseResultDto().SetError("用户不存在！"));
        }

        await _userManager.DeleteAsync(user);
        return NoContent();
    }

    /// <summary>
    /// 获取所有用户列表
    /// </summary>
    /// <returns></returns>
    [HttpGet("all")]
    public IActionResult GetAll()
    {
        var list = _userService.GetAll();
        return Ok(list);
    }
}